package com.sdry.web.filter;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.utils.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 拦截器：拦截  .do  路径
 * @ClassName:    LoginInterceptor
 * @Description:  多仓库修改  t  2019-10-31 223-228：支持多仓库：登陆：放行查询仓库信息方法（登陆使用对应第2条）、放行APP查询仓库信息方法
 * @Author:       zc
 * @CreateDate:   2019年4月17日 下午4:10:42   
 * @Version:      v1.0
 */
@Controller
public class LoginInterceptor implements HandlerInterceptor {
    //进入 Handler方法之前执行
    //用于身份认证、身份授权
    //比如身份认证，如果认证通过表示当前用户没有登陆，需要此方法拦截不再向下执行
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //获取请求的url
        String url = request.getRequestURI();
        //判断url是否是公开 地址（实际使用时将公开 地址配置配置文件中）//这里公开地址是登陆提交的地址
        //登陆
        if(url.indexOf("system/toIndex.do")>=0){
            //进入首页
            return true;
        }
        if(url.indexOf("login/pclogin.do")>=0){
            //如果进行登陆提交，放行
            return true;
        }

        if(url.indexOf("login/appLogin.do")>=0){
            //如果进行app登陆提交，放行
            return true;
        }
        if(url.indexOf("inventoryManagement/selectInventoryInfoByCodeApp.do")>=0){
            //如果通过产品码或简码查询库存，放行
            return true;
        }
        if(url.indexOf("inventoryManagement/selectInventoryInfoByCodeApp2.do")>=0){
            //如果通过产品码或简码查询库存，放行
            return true;
        }
        if(url.indexOf("inventoryManagement/appMove.do")>=0){
            //如果通过移库，放行
            return true;
        }
        if(url.indexOf("inventoryManagement/appMove2.do")>=0){
            //如果通过移库，放行
            return true;
        }
        if(url.indexOf("inventoryManagement/selectStockWarningList.do")>=0){
            //如果通过预警，放行
            return true;
        }
        if(url.indexOf("rejectsWarehouse/selectRejectsWarehouseListApp.do")>=0){
            //如果不良品，放行
            return true;
        }

        if(url.indexOf("stockOutOrder/queryOutStockOrderAndroid.do")>=0){
            //出库单查询，放行
            return true;
        }
        if(url.indexOf("stockOutOrder/queryOutStockOrderDetailByIdAndroid.do")>=0){
            //根据出库单id查询出库单详情，放行
            return true;
        }
        if(url.indexOf("stockOutOrder/triggerWarning.do")>=0){
            //根据查询库存预警值，放行
            return true;
        }
        if(url.indexOf("stockOutOrder/updateStockOutOrderDetailStatusAndroid.do")>=0){
            //根据安卓扫码匹配物料出库，放行
            return true;
        }
        //APP段的访问，都放行
        if(url.equals("/login/appLogin.do")
                || url.equals("/appManager/getAllStock.do")
                || url.equals("/inventoryManagement/selectMaterielSizeByCodeApp.do")
                || url.equals("/inventoryManagement/selectMaterielSizeByCodeApp2.do")
                || url.equals("/inventoryManagement/selectMaterielInfoByCodeApp.do")
                || url.equals("/inventoryManagement/selectWarehouseRegionListApp.do")
                || url.equals("/inventoryManagement/appMove.do")
                || url.equals("/inventoryManagement/selectStockWarningList.do")
                || url.equals("/rejectsWarehouse/selectRejectWareListApp.do")
                || url.equals("/rejectsWarehouse/selectRejectsWarehouseListApp.do")
                || url.equals("/rejectsWarehouse/enterRejectsApp.do")
                || url.equals("/bindAndUnbind/bindingMaterielAndTrayApp.do")
                || url.equals("/bindAndUnbind/unbindMaterielAndTrayApp.do")
                || url.equals("/bindAndUnbind/selectMaterielInfoByCodeApp.do")
                || url.equals("/bindAndUnbind/selectMaterielLocationByCodeApp.do")
                || url.equals("/bindAndUnbind/bindAndUp2SpecialArea.do")
                || url.equals("/bindAndUnbind/bindAndUp2SpecialAreaUp.do")
                || url.equals("/bindAndUnbind/selectMaterielLocationByCodeAppDown.do")
                || url.equals("/upAndDown/bindingTrayAndLocationApp.do")
                || url.equals("/upAndDown/unbindTrayAndLocationApp.do")
                || url.equals("/stockOutOrder/appSubmitOutStockOrderDetailJudge.do")
        		/*|| url.equals("/appManager/getAllStock.do")
        		|| url.equals("/inventoryManagement/selectInventoryInfoByCodeApp2.do")
        		|| url.equals("/inventoryManagement/appMove2.do")*/

                //测试勿扰
                || url.equals("/anomalyRecords/getAnomalyRecordsList.do" )

                || url.equals("/appManager/stocksearch.do")
                || url.equals("/comeKu/comeku.do")
                || url.equals("/comeKuDetail/selectBycomeNumber.do")
                || url.equals("/comeKuDetail/updateComku.do")
                || url.equals("/appdeliverplan.do")
                || url.equals("/receive/receiving.do")
                || url.equals("/comeKuDetail/selectWait.do")
                || url.equals("/up/up.do")
                || url.equals("/inventory/queryInventoryOrderCriteriaAndroid.do")
                || url.equals("/inventory/queryInventoryDetailCriteriaByIdAndroid.do")
                || url.equals("/inventory/queryInventoryDetailCriteriaByIdAndroid2.do")
                || url.equals("/inventory/updateInventoryDetailAndroid.do")
                || url.equals("/receiveDetail/selectDtailByNumber.do")
                || url.equals("/receiveDetail/updateById.do")
                || url.equals("/receiveDetailCode/selectCodesByrdid.do")
                || url.equals("/receiveDetailCode/updateById.do")
                || url.equals("/stockOutOrder/queryOutStockOrderAndroid.do")
                || url.equals("/stockOutOrder/queryOutStockOrderDetailByIdAndroid.do")
                || url.equals("/inventory/queryInventoryOrderCriteriaAndroid.do")
                || url.equals("/appInterfaces/appGetCancellingStock.do")
                || url.equals("/appInterfaces/appGetCancellingStockDetailByNumber.do")
                || url.equals("/appInterfaces/appSubmitCancellingStockDetail.do")
                || url.equals("/appInterfaces/appGetMaterielByCustomerAndSAP.do")
                || url.equals("/appInterfaces/appGetLocationByNumber.do")
                //收货入库
                || url.equals("/appUnpackingTask.do")
                || url.equals("/appFindKqByUid.do")
                || url.equals("/appUnpackingTaskXj.do")
                || url.equals("/appUnpackingTaskSj.do")
                || url.equals("/app/selectAllReceive.do")
                || url.equals("/app/selectReceiveDtailByNumber.do")
                || url.equals("/app/submitReceive.do")
                || url.equals("/app/selectMaByMaNum.do")
                || url.equals("/app/selectWarehouseByMid.do")
                || url.equals("/app/comeku.do")
                || url.equals("/app/ngInstock.do")
                || url.equals("/app/selectAccurateByCodeApp.do")
                || url.equals("/app/selectAccurateByCodeApp2.do")
                || url.equals("/app/queryReceiveDetailQualityAPP.do")
                || url.equals("/app/queryReceiveDetailQualityAPP1.do")
                || url.equals("/app/updateReceiveDetailQualityAPP.do")
                || url.equals("/app/devanning.do")
                || url.equals("/app/queryRepeatAccurateByCodeApp.do")
                || url.equals("/app/selectAccurateByCodeAppInventory.do")
                || url.equals("/app/queryRoleUser.do")
                || url.equals("/app/queryReceiveCodeByReceiveId.do")
                //计数收货
                || url.equals("/app/selectAllReceipt.do")
                || url.equals("/app/selectReceiptDtailByNumber.do")
                || url.equals("/app/submitReceipt.do")
                //退库
                || url.equals("/rejectsWarehouse/selectRejectWareListApp.do")
                || url.equals("/rejectsWarehouse/enterRejectsApp.do")
                //出库
                || url.equals("/stockOutOrder/queryOutStockOrderForPDA.do")
                || url.equals("/stockOutOrder/queryOutStockOrderDetailByIdForPDA.do")
                || url.equals("/stockOutOrder/appSubmitOutStockOrderDetail.do")
                || url.equals("/stockOutOrder/queryDeliveryOrderForPDA.do")
                || url.equals("/stockOutOrder/appSubmitDeliveryOrderDetail.do")
                //紧急出库
                || url.equals("/stockOutOrder/queryQualityMaterielOut.do")
                || url.equals("/stockOutOrder/queryUrgencyOrderForPDA.do")
                || url.equals("/stockOutOrder/appSubmitUrgencyOrderDetail.do")
                || url.equals("/app/urgencySelectAccurateByCodeApp.do")
                //配送
                || url.equals("/DeliveryNode/queryOutStockByUserId.do")
                || url.equals("/DeliveryNode/queryOutStockDetailByOrderId.do")
                || url.equals("/DeliveryNode/updateDeliveryStatus.do")
                || url.equals("/DeliveryNode/updateOutStockDetail.do")
                //拆箱计划
                || url.equals("/unpackDetal/selectAllUnpacking.do")
                || url.equals("/unpackDetal/devanning.do")
                || url.equals("/unpackDetalCode/selectDevanningByCodeApp.do")
                //配货计划
                || url.equals("/appPrepare/selectPrepareOneByNumber.do")
                || url.equals("/appPrepare/selectPrepareDtailByNumber.do")
                || url.equals("/appPrepare/peihou.do")
                || url.equals("/bindAndUnbind/bindAndUp2SpecialArea2.do")
                || url.equals("/bindAndUnbind/bindAndUp2SpecialArea3.do")
                //错误信息保存
                || url.equals("/app/error.do")
                //app版本更新
                || url.equals("/version/getLatestVersion.do")
                //查询条码是否存在
                || url.equals("/app/queryLifeByCode.do")
                //查询条码是否存在
                //批量退库
                || url.equals("/CancellingStocksDetailPiLiang/appGetCancellingStock.do")
                || url.equals("/CancellingStocksDetailPiLiang/selectLlmCancellingStocksDetailByCancellingNumber.do")
                || url.equals("/CancellingStocksDetailPiLiang/piLiangSubmission.do")
                //批量出库单查询
                || url.equals("/outStockOrderDetail2/outStockOrderPiLiang.do")
                //根据出库单id查询出库单详情
                || url.equals("/outStockOrderDetail2/outStockOrderDetail2ByOut_stock_num_id.do")
                //批量出库提交
                || url.equals("/outStockOrderDetail2/piLiangSubmission.do")
                || url.equals("/simple/selectMaFromHc.do")
                || url.equals("/simple/simpleUp.do")
                || url.equals("/simple/selectMaFromDown.do")
                || url.equals("/simple/simpleDown.do")
                || url.equals("/simple/selectAllReceipt.do")
                || url.equals("/simple/submitReceipt.do")
                || url.equals("/simple/selectAllUnpacking.do")
                || url.equals("/simple/devanning.do")
                //线边库
                || url.equals("/storageAreaManager/selectMaByCustomer.do")
                || url.equals("/storageAreaManager/submitStorage.do")
                //传送经纬度
                || url.equals("/car/receiveVehicleTransInfo.do")
                //看板
                || url.equals("/spectaculars/inventory.do")
                || url.equals("/spectaculars/removeal.do")
                || url.equals("/spectaculars/appReport.do")
                /* ******************************多仓库修改  t  2019-10-31 开始***************************  */
                //登陆查询所有仓库
                || url.equals("/warehouse/queryAllWarehouse.do")
                //app查找所有仓库
                || url.equals("/warehouse/aPPQueryAllWarehouse.do")
                /* ******************************多仓库修改  t  2019-10-31 结束***************************  */

                //上架前库位校验
                || url.equals("/bindAndUnbind/selectLocationExist.do")
                /****************************不用登陆，直接访问个站点的报表*********************************************/
                || url.equals("/tabReport.do")
                //日报表
                || url.equals("/report/queryDateReport.do")
                || url.equals("/report/exportallDateBalance.do")

                || url.equals("/report/queryMonthReport.do")
                || url.equals("/report/exportallReportFormList.do")

                || url.equals("/report/queryStoreInWareHouse.do")
                || url.equals("/report/exportReportFormJinList.do")

                || url.equals("/report/queryStoreOutWareHouse.do")
                || url.equals("/report/exportReportFormChungList.do")


                || url.equals("/report/queryStoreReturnWareHouse.do")
                || url.equals("/report/exportReportFormReTurnList.do")


                || url.equals("/report/queryStoreRejectsWareHouse.do")
                || url.equals("/report/exportReportFormReGeLIList.do")



                //所有的供应商
                || url.equals("/reportForm/queryAllCustomerByWareHouseList.do")
        ){
            return true;
        }
        //判断session
        HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        ZcSysUserEntity userSession = (ZcSysUserEntity) session.getAttribute("user");
        //请求头的状态
        String type = request.getHeader("X-Requested-With");
        if(userSession != null){
            //身份存在，放行
            return true;
        }
        //针对ajax进行拦截，cb_2019年11月13日15:54:02
        if ("XMLHttpRequest".equalsIgnoreCase(type)) {
            response.setHeader("sessionstatus","timeout");
            return false;
        }
        response.sendRedirect("/index.jsp");
        return false;
    }

    //进入Handler方法之后，返回modelAndView之前执行
    //应用场景从modelAndView出发：将公用的模型数据(比如菜单导航)在这里传到视图，也可以在这里统一指定视图
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }
    //执行Handler完成执行此方法
    //应用场景：统一异常处理，统一日志处理
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
    public static String getuserbrowser(HttpServletRequest request) {
        //String Agent = request.getHeader("User-Agent");
        //StringTokenizer st = new StringTokenizer(Agent,";");
        //st.nextToken();
        //得到用户的浏览器名
        //String userbrowser = st.nextToken();
        //得到用户的操作系统名
        //String useros = st.nextToken();

        String agent=request.getHeader("User-Agent").toLowerCase();
        System.out.println("浏览器版本："+getBrowserName(agent));
        return getBrowserName(agent);
    }


    public static String getBrowserName(String agent) {
        if(agent.indexOf("msie 7")>0){
            return "ie7";
        }else if(agent.indexOf("msie 8")>0){
            return "ie8";
        }else if(agent.indexOf("msie 9")>0){
            return "ie9";
        }else if(agent.indexOf("msie 10")>0){
            return "ie10";
        }else if(agent.indexOf("msie")>0){
            return "ie";
        }else if(agent.indexOf("opera")>0){
            return "opera";
        }else if(agent.indexOf("opera")>0){
            return "opera";
        }else if(agent.indexOf("firefox")>0){
            return "firefox";
        }else if(agent.indexOf("webkit")>0){
            return "webkit";
        }else if(agent.indexOf("gecko")>0 && agent.indexOf("rv:11")>0){
            return "ie11";
        }else{
            return "Others";
        }
    }
}
